<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="finishTime">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.finishTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择结束时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态 " prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态 " clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['travel:scenic:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['travel:scenic:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['travel:scenic:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['travel:scenic:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="scenicList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="景区名称" align="center" prop="name" :show-overflow-tooltip="true" />
      <!-- <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true" /> -->
      <el-table-column label="景区电话" align="center" prop="mobile" width="160" />
      <el-table-column label="地址" align="center" prop="address" :show-overflow-tooltip="true" />
      <!-- <el-table-column label="经度" align="center" prop="log" /> -->
      <!-- <el-table-column label="纬度" align="center" prop="lat" /> -->
      <el-table-column label="门票价格" align="center" prop="price" />
      <!-- <el-table-column label="主图" align="center" prop="images" :show-overflow-tooltip="true" /> -->
      <!-- <el-table-column label="其他图片" align="center" prop="otherImg" :show-overflow-tooltip="true" /> -->
      <el-table-column label="标签" align="center" prop="tag" />
      <el-table-column label="类型" align="center" prop="type" :formatter="typeFormat" />
      <el-table-column label="状态 " align="center" prop="status" :formatter="statusFormat" />
      <!-- <el-table-column label="操作人编号" align="center" prop="operatorId" /> -->
			<el-table-column label="开始时间" align="center" prop="startTime" width="160">
			  <template slot-scope="scope">
			    <span>{{ parseTime(scope.row.startTime) }}</span>
			  </template>
			</el-table-column>
			<el-table-column label="结束时间" align="center" prop="finishTime" width="160">
			  <template slot-scope="scope">
			    <span>{{ parseTime(scope.row.finishTime) }}</span>
			  </template>
			</el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['travel:scenic:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['travel:scenic:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改景区 对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="名称" prop="name">
						  <el-input v-model="form.name" placeholder="请输入名称" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="景区电话" prop="mobile">
						  <el-input v-model="form.mobile" placeholder="请输入景区电话" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col span="12">
						<el-form-item label="开始时间" prop="startTime">
						  <el-date-picker clearable size="small" style="width: 100%"
						    v-model="form.startTime"
						    type="date"
						    value-format="yyyy-MM-dd"
						    placeholder="选择开始时间">
						  </el-date-picker>
						</el-form-item>
					</el-col>
					<el-col span="12">
						<el-form-item label="结束时间" prop="finishTime">
						  <el-date-picker clearable size="small" style="width: 100%"
						    v-model="form.finishTime"
						    type="date"
						    value-format="yyyy-MM-dd"
						    placeholder="选择结束时间">
						  </el-date-picker>
						</el-form-item>
					</el-col>
				</el-row>
        <el-row>
        	<el-col span="12">
        		<el-form-item label="标签" prop="tag">
        		  <el-input v-model="form.tag" placeholder="请输入标签" />
        		</el-form-item>
        	</el-col>
        	<el-col span="12">
        		<el-form-item label="类型">
        		  <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%;">
        		    <el-option
        		      v-for="dict in typeOptions"
        		      :key="dict.dictValue"
        		      :label="dict.dictLabel"
        		      :value="dict.dictValue"
        		    ></el-option>
        		  </el-select>
        		</el-form-item>
        	</el-col>
        </el-row>
				<el-row>
					<el-col span="12">
						<el-form-item label="门票价格" prop="price">
						  <el-input v-model="form.price" placeholder="请输入门票价格" />
						</el-form-item>
					</el-col>
					<el-col span="12">
						<el-form-item label="地址" prop="address">
						  <el-input v-model="form.address" type="input" placeholder="请输入内容" />
						</el-form-item>
					</el-col>
				</el-row>
        <el-row>
          <el-col span="12">
            <el-form-item label="经度" prop="log">
              <el-input v-model="form.log" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
          <el-col span="12">
            <el-form-item label="纬度" prop="lat">
              <el-input v-model="form.lat" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="状态 ">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="主图" prop="images">
          <el-upload
            action="https://jsonplaceholder.typicode.com/posts/"
            list-type="picture-card"
            :limit="1"
            :multiple="false"
            :file-list="mianFileLists"
            :on-change="mainImgBeforeupload"
            :auto-upload="false"
            :on-success="unloadSuccess"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="其他图片" prop="otherImg">
          <el-upload
            action="https://jsonplaceholder.typicode.com/posts/"
            list-type="picture-card"
            :limit="5"
            :multiple="true"
            :file-list="orderFileLists"
            :on-change="orderImgBeforeupload"
            :auto-upload="false"
            :on-success="unloadSuccess"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>


       <!-- <el-form-item label="主图" prop="images">
          <el-input v-model="form.images" type="textarea" placeholder="请输入主图地址" />
        </el-form-item>
        <el-form-item label="其他图片" prop="otherImg">
          <el-input v-model="form.otherImg" type="textarea" placeholder="图片地址以逗号隔开" />
        </el-form-item> -->


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listScenic, getScenic, delScenic, addScenic, updateScenic, exportScenic, delImg } from "@/api/travel/scenic";

export default {
  name: "Scenic",
  data() {
    return {
      // 展示图url
      dialogImageUrl: '',
      // 展示图是否显示
      dialogVisible: false,
      //主图文件
      mainImgs: null,
      //其他图片文件
      orderImgs: [],
      //修改时默认图片
      // fileLists: [{name: 'food.jpg', url: 'https://img.myliwoo.top/advertising/202006/0913423212540d7_original.jpg'},{name: 'food.jpg', url: 'https://img.myliwoo.top/advertising/202006/0913423212540d7_original.jpg'}],
      mianFileLists: [],//主图
      orderFileLists:[],//其他图片
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 景区 表格数据
      scenicList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型字典
      typeOptions: [],
      // 状态 字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        startTime: undefined,
        finishTime: undefined,
        tag: undefined,
        type: undefined,
        status: undefined,
      },
      // 上传参数
      // formData: new FormData(),
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("tr_scenic_type").then(response => {
      this.typeOptions = response.data;
    });
    this.getDicts("tr_scenic_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    // 主图上传前
    mainImgBeforeupload (file) {
      this.mainImgs = file.raw;
      console.log(this.mainImgs);
      return false
    },
    // 其他上传图
    orderImgBeforeupload (file) {
      this.orderImgs.push(file.raw);
      console.log(this.orderFileLists);
      return false
    },
    //上传成功
    unloadSuccess(response, file, fileLis) {
      console.log(response);
    },
    //移除图片
    handleRemove(file, fileList) {
      if(file.status == "ready"){  //未上传的图
        if(file.name == this.mainImgs.name){
          this.mainImgs = null;
        }else{
          for(let i=0;i<this.orderImgs.length;i++){
            if(file.name == this.orderImgs[i].name){
              this.orderImgs.splice(i, 1);
            }
          }
        }
      }else if(file.status == "success"){//已上传的图
        let param = {
          scenicId:this.form.id,
          type:0,
          delImg:'',
          photoPath:''
        }
        param.delImg = file.name;
        if(this.mianFileLists.length > 0 && file.name == this.mianFileLists[0].name){
          this.mianFileLists = [];
          this.form.images = "";
        }else{
          param.type = 1;
          let orderImgArr = [];
          for(let i=0;i<fileList.length;i++){
            if(fileList[i].status == "success"){
              orderImgArr.push(fileList[i].name);
            }
          }
          this.form.otherImg = orderImgArr.join(",");
          param.photoPath = orderImgArr.join(",");
        }
        delImg(param).then(response => {
          this.msgSuccess("图片已删除");
        });
      }
      // console.log(file, fileList);
      // console.log("mainImgs", this.mainImgs);
      // console.log("orderImgs", this.orderImgs);
      // console.log("mianFileLists", this.mianFileLists);
      // console.log("orderFileLists", this.orderFileLists);
      // console.log("form", this.form);
    },
    // 预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    /** 查询景区 列表 */
    getList() {
      this.loading = true;
      listScenic(this.queryParams).then(response => {
        this.scenicList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 状态 字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: undefined,
        description: undefined,
        mobile: undefined,
        address: undefined,
        log: undefined,
        lat: undefined,
        price: undefined,
        images: undefined,
        otherImg: undefined,
        startTime: undefined,
        finishTime: undefined,
        tag: undefined,
        type: undefined,
        status: "0",
      };
      this.mianFileLists = [];//主图
      this.orderFileLists = [];//其他图片
      this.mainImgs = null;
      this.orderImgs = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加景区 ";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getScenic(id).then(response => {
				response.data.status = response.data.status + "";
				response.data.type = response.data.type + "";
        this.form = response.data;
        this.mianFileLists = this.jointImageUrl(this.form.images);
        this.orderFileLists = this.jointImageUrl(this.form.otherImg);
        this.open = true;
        this.title = "修改景区 ";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        let formData = new FormData();
        formData.append("images",this.form.images);
        formData.append("otherImg",this.form.otherImg);
        formData.append("name",this.form.name);
        formData.append("description",this.form.description);
        formData.append("mobile",this.form.mobile);
        formData.append("address",this.form.address);
        formData.append("log",this.form.log);
        formData.append("lat",this.form.lat);
        formData.append("price",this.form.price);
        formData.append("startTime",this.form.startTime);
        formData.append("finishTime",this.form.finishTime);
        formData.append("tag",this.form.tag);
        formData.append("type",this.form.type);
        formData.append("status",this.form.status);
        if (valid) {
          if (this.form.id != undefined) {
            if(this.mainImgs == null && (this.form.images == "" || this.form.images == null)){
              this.msgError("需要上传主图");
              return;
            }else if(this.orderImgs.length <= 0 && (this.form.otherImg == "" || this.form.otherImg == null)){
              this.msgError("需要上传其他图片");
              return;
            }
            formData.append("id",this.form.id);
            if(this.mainImgs != null){
              formData.append("mainImgs",this.mainImgs);
            }
            if(this.orderImgs != null && this.orderImgs.length > 0){
              for(let item of this.orderImgs){
                formData.append("orderImgs",item);
              }
            }
            updateScenic(formData).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            if(this.mainImgs == null){
              this.msgError("需要上传主图");
              return;
            }else if(this.orderImgs == null){
              this.msgError("需要上传其他图片");
              return;
            }
            for(let item of this.orderImgs){
              formData.append("orderImgs",item);
            }
            formData.append("mainImgs",this.mainImgs);
            addScenic(formData).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除景区 编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delScenic(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有景区 数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportScenic(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
<style>
  .v-modal{
    z-index: 2000 !important;
  }
</style>
